package com.system.runtai.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.system.common.result.Result;
import com.system.runtai.entity.*;
import com.system.runtai.service.*;
import com.system.runtai.utils.AuthContextUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 行业动态 前端控制器
 * </p>
 *
 * @author runtai
 * @since 2024-03-29
 */
@Api(tags = "行业动态")
@RestController
@RequestMapping("/runtai/posted")
public class PostedController {

    @Autowired
    private AppletUserService appletUserService;

    @Autowired
    private PostedService postedService;

    @Autowired
    private EnterService enterService;

    @Autowired
    private IpaEnterService ipaEnterService;

    @Autowired
    private PostedCollectService postedCollectService;

    @Autowired
    private PostedDiscussService postedDiscussService;

    @Autowired
    private UpvoteService upvoteService;

    @Autowired
    private HomePageService homePageService;

    @ApiOperation(value = "后台：所有行业动态")
    @GetMapping("postedList")
    public Result<IPage<Posted>> postedList(@RequestParam(required = false) Integer page, @RequestParam(required = false) Integer limit){
        Page<Posted> recommendPage = new Page<>(page,limit);
        IPage<Posted> iPage = postedService.page(recommendPage);
        return Result.ok(iPage);
    }


    @ApiOperation(value = "程序：行业动态轮播图")
    @GetMapping("postedPictore")
    public Result<HomePage> postedPictore(){
        LambdaQueryWrapper<HomePage> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(HomePage::getStart,2);
        HomePage list = homePageService.getOne(wrapper);
        return Result.ok(list);
    }


    @ApiOperation(value = "程序：所有行业动态")
    @GetMapping("cxList")
    public Result<IPage<Posted>> cxList(@RequestParam(required = false) String intro,@RequestParam(required = false) Integer page, @RequestParam(required = false) Integer limit){
        String s = AuthContextUtil.get();

        if (StringUtils.isEmpty(intro)){
            LambdaQueryWrapper<Posted> wrapper = new LambdaQueryWrapper<>();
            wrapper.orderByDesc(Posted::getCreateTime);
            List<Posted> list = postedService.list(wrapper);
            Page<Posted> recommendPage = new Page<>(page,limit);
            IPage<Posted> iPage = postedService.page(recommendPage,wrapper);
            for (Posted record : iPage.getRecords()) {
                LambdaQueryWrapper<Upvote> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(Upvote::getAppletUserId,Integer.valueOf(s)).eq(Upvote::getCommentid,1).eq(Upvote::getDynamicid,record.getId());
                Upvote one = upvoteService.getOne(wrapper1);

                if (one!=null){
                    record.setLike(1);
                }else {
                    record.setLike(0);
                }

                LambdaQueryWrapper<PostedCollect> wrapper2 = new LambdaQueryWrapper<>();
                wrapper2.eq(PostedCollect::getAppletUserId,Integer.valueOf(s)).eq(PostedCollect::getPostedId,record.getId());
                PostedCollect one1 = postedCollectService.getOne(wrapper2);

                if (one1!=null){
                    record.setCollect(1);
                }else {
                    record.setCollect(0);
                }

            }

            return Result.ok(iPage);
        }else if (!StringUtils.isEmpty(intro)) {
            LambdaQueryWrapper<Posted> wrapper = new LambdaQueryWrapper<>();
            wrapper.like(Posted::getIntro, intro).orderByDesc(Posted::getCreateTime);
            List<Posted> list = postedService.list(wrapper);
            Page<Posted> recommendPage = new Page<>(page,limit);
            IPage<Posted> iPage = postedService.page(recommendPage,wrapper);
            for (Posted record : iPage.getRecords()) {
                LambdaQueryWrapper<Upvote> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(Upvote::getAppletUserId,Integer.valueOf(s)).eq(Upvote::getCommentid,1).eq(Upvote::getDynamicid,record.getId());
                Upvote one = upvoteService.getOne(wrapper1);

                if (one!=null){
                    record.setLike(1);
                }else {
                    record.setLike(0);
                }

                LambdaQueryWrapper<PostedCollect> wrapper2 = new LambdaQueryWrapper<>();
                wrapper2.eq(PostedCollect::getAppletUserId,Integer.valueOf(s)).eq(PostedCollect::getPostedId,record.getId());
                PostedCollect one1 = postedCollectService.getOne(wrapper2);

                if (one1!=null){
                    record.setCollect(1);
                }else {
                    record.setCollect(0);
                }

            }

            return Result.ok(iPage);
        }
        Page<Posted> recommendPage = new Page<>(page,limit);
        IPage<Posted> iPage = null;
        return Result.fail(iPage).message("查询数据失败");
    }

    @ApiOperation(value = "程序：所有行业动态（热门）")
    @GetMapping("remenList")
    public Result<IPage<Posted>> remenList(@RequestParam(required = false) String intro,@RequestParam(required = false) Integer page, @RequestParam(required = false) Integer limit){
        String s = AuthContextUtil.get();
        if (StringUtils.isEmpty(intro)){
            LambdaQueryWrapper<Posted> wrapper = new LambdaQueryWrapper<>();
            wrapper.orderByDesc(Posted::getNumber);
            List<Posted> list = postedService.list(wrapper);
            Page<Posted> recommendPage = new Page<>(page,limit);
            IPage<Posted> iPage = postedService.page(recommendPage,wrapper);

            for (Posted record : iPage.getRecords()) {
                LambdaQueryWrapper<Upvote> wrapper3 = new LambdaQueryWrapper<>();
                wrapper3.eq(Upvote::getAppletUserId,Integer.valueOf(s)).eq(Upvote::getCommentid,1).eq(Upvote::getDynamicid,record.getId());
                Upvote one = upvoteService.getOne(wrapper3);

                if (one!=null){
                    record.setLike(1);
                }else {
                    record.setLike(0);
                }

                LambdaQueryWrapper<PostedCollect> wrapper2 = new LambdaQueryWrapper<>();
                wrapper2.eq(PostedCollect::getAppletUserId,Integer.valueOf(s)).eq(PostedCollect::getPostedId,record.getId());
                PostedCollect one1 = postedCollectService.getOne(wrapper2);

                if (one1!=null){
                    record.setCollect(1);
                }else {
                    record.setCollect(0);
                }

            }

            return Result.ok(iPage);
        }else if (!StringUtils.isEmpty(intro)) {
            LambdaQueryWrapper<Posted> wrapper = new LambdaQueryWrapper<>();
            wrapper.like(Posted::getIntro, intro).orderByDesc(Posted::getNumber);
            List<Posted> list = postedService.list(wrapper);
            Page<Posted> recommendPage = new Page<>(page,limit);
            IPage<Posted> iPage = postedService.page(recommendPage,wrapper);

            for (Posted record : iPage.getRecords()) {
                LambdaQueryWrapper<Upvote> wrapper3 = new LambdaQueryWrapper<>();
                wrapper3.eq(Upvote::getAppletUserId,Integer.valueOf(s)).eq(Upvote::getCommentid,1).eq(Upvote::getDynamicid,record.getId());
                Upvote one = upvoteService.getOne(wrapper3);

                if (one!=null){
                    record.setLike(1);
                }else {
                    record.setLike(0);
                }

                LambdaQueryWrapper<PostedCollect> wrapper2 = new LambdaQueryWrapper<>();
                wrapper2.eq(PostedCollect::getAppletUserId,Integer.valueOf(s)).eq(PostedCollect::getPostedId,record.getId());
                PostedCollect one1 = postedCollectService.getOne(wrapper2);

                if (one1!=null){
                    record.setCollect(1);
                }else {
                    record.setCollect(0);
                }

            }

            return Result.ok(iPage);
        }
        Page<Posted> recommendPage = new Page<>(page,limit);
        IPage<Posted> iPage = null;
        return Result.fail(iPage).message("查询数据失败");
    }

    @ApiOperation(value = "自己发布的行业动态")
    @GetMapping("miList")
    public Result<IPage<Posted>> miList(@RequestParam(required = false) Integer page, @RequestParam(required = false) Integer limit){
        String s = AuthContextUtil.get();
        LambdaQueryWrapper<Posted> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Posted::getAppletUserId,Integer.valueOf(s)).orderByDesc(Posted::getCreateTime);
        List<Posted> list = postedService.list(wrapper);

        Page<Posted> recommendPage = new Page<>(page,limit);
        IPage<Posted> iPage = postedService.page(recommendPage,wrapper);
        return Result.ok(iPage);
    }

    @ApiOperation(value = "行业动态详情，评论、点赞")
    @GetMapping("posted/{id}")
    public Result<Posted> postedList(@PathVariable Integer id){


        String s = AuthContextUtil.get();
        Posted byId = postedService.getById(id);
        byId.setNumber(byId.getNumber()+1);
        postedService.updateById(byId);

        LambdaQueryWrapper<PostedDiscuss> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PostedDiscuss::getPostedid,byId.getId());
        List<PostedDiscuss> list = postedDiscussService.list(wrapper);

        LambdaQueryWrapper<Upvote> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Upvote::getDynamicid,byId.getId()).eq(Upvote::getCommentid,1);
        List<Upvote> list1 = upvoteService.list(wrapper1);



        LambdaQueryWrapper<Upvote> wrapper3 = new LambdaQueryWrapper<>();
        wrapper3.eq(Upvote::getAppletUserId,Integer.valueOf(s)).eq(Upvote::getCommentid,1).eq(Upvote::getAppletUserId,Integer.valueOf(s));
        Upvote one = upvoteService.getOne(wrapper3);

        if (one!=null){
            byId.setLike(1);
        }else {
            byId.setLike(0);
        }

        LambdaQueryWrapper<PostedCollect> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(PostedCollect::getAppletUserId,Integer.valueOf(s));
        PostedCollect one1 = postedCollectService.getOne(wrapper2);

        if (one1!=null){
            byId.setCollect(1);
        }else {
            byId.setCollect(0);
        }


        byId.setDiscussList(list);
        byId.setUpvoteList(list1);
        return Result.ok(byId);
    }


    @ApiOperation(value = "添加行业动态")
    @PostMapping("postedById")
    public Result<Posted> postedById(@RequestBody Posted posted){

        String s = AuthContextUtil.get();

        LambdaQueryWrapper<IpaEnter> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(IpaEnter::getAppletUserId, Integer.valueOf(s));
        IpaEnter one = ipaEnterService.getOne(wrapper);
//        if (one.getStart()==1){
            AppletUser byId = appletUserService.getById(Integer.valueOf(s));

            posted.setAppletUserId(byId.getId());
            posted.setAvatar(byId.getAvatar());
            posted.setNickName(one.getName());
            posted.setCompany(one.getCompany());
            posted.setCreateTime(LocalDateTime.now());
            posted.setAdvertising(byId.getStart());
            posted.setLike(0);
            posted.setCollect(0);
            boolean save = postedService.save(posted);

            if (save){
                return Result.ok(posted).message("添加行业动态成功");
            }
            return Result.fail(posted).message("添加行业动态失败");

//        }
//
//        return Result.fail(posted).message("入驻未通过审核，暂不能发布动态");
    }


    @ApiOperation(value = "添加行业社区动态收藏")
    @PostMapping("/saveCollect")
    public Result<PostedCollect> saveCollect(@RequestBody Posted posted){
        String s = AuthContextUtil.get();
        LambdaQueryWrapper<PostedCollect> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PostedCollect::getPostedId,posted.getId()).eq(PostedCollect::getAppletUserId,Integer.valueOf(s));
        PostedCollect one = postedCollectService.getOne(wrapper);

        if (one!=null){
            return Result.ok(one);
        }else {
            PostedCollect postedCollect = new PostedCollect();
            postedCollect.setCreateTime(LocalDateTime.now());
            postedCollect.setPostedId(posted.getId());
            postedCollect.setAppletUserId(Integer.valueOf(s));
            boolean save = postedCollectService.save(postedCollect);

            if (save){
                posted.setCollectNum(posted.getCollectNum()+1);
                postedService.updateById(posted);
                return Result.ok(postedCollect).message("添加行业收藏成功");
            }
            return Result.fail(postedCollect).message("添加行业收藏失败");
        }
    }


    @ApiOperation(value = "修改已完成状态")
    @PostMapping("/updatePosted")
    public Result updatePoster(@RequestBody Posted posted){

        posted.setStart(1);
        boolean b = postedService.updateById(posted);

        if (b){
            return Result.ok().message("已完成修改");
        }
        return Result.fail().message("修改失败");
    }

    @ApiOperation(value = "删除行业动态")
    @PostMapping("/delectPosted")
    public Result delectPosted(@RequestBody Posted posted){

        String s = AuthContextUtil.get();

        LambdaQueryWrapper<PostedDiscuss> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PostedDiscuss::getAppletUserId,Integer.valueOf(s)).eq(PostedDiscuss::getPostedid,posted.getId());
        boolean remove = postedDiscussService.remove(wrapper);

        LambdaQueryWrapper<Upvote> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Upvote::getDynamicid,posted.getId()).eq(Upvote::getCommentid,1).eq(Upvote::getAppletUserId,Integer.valueOf(s));
        boolean remove1 = upvoteService.remove(queryWrapper);
        boolean b = postedService.removeById(posted.getId());
        if (b){
            return Result.ok().message("删除成功");
        }
        return Result.fail().message("删除失败");
    }


    @ApiOperation(value = "取消行业动态收藏")
    @PostMapping("/delectPostedCollect")
    public Result delectPostedCollect(@RequestBody Posted posted){

        String s = AuthContextUtil.get();
        LambdaQueryWrapper<PostedCollect> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PostedCollect::getPostedId,posted.getId()).eq(PostedCollect::getAppletUserId,Integer.valueOf(s));
        boolean b = postedCollectService.remove(wrapper);

        if (b){
            posted.setCollectNum(posted.getCollectNum()-1);
            postedService.updateById(posted);
            return Result.ok().message("取消行业动态收藏成功");
        }
        return Result.fail().message("取消行业动态收藏失败");
    }

    @ApiOperation(value = "行业动态添加评论")
    @PostMapping("/saveComment")
    public Result saveComment(@RequestBody PostedDiscuss postedD){

        String s = AuthContextUtil.get();
        PostedDiscuss postedDiscuss = new PostedDiscuss();
        postedDiscuss.setPostedid(postedD.getFId());
        LambdaQueryWrapper<IpaEnter> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(IpaEnter::getAppletUserId,Integer.valueOf(s));
        IpaEnter one = ipaEnterService.getOne(wrapper);
        postedDiscuss.setAppletUserId(Integer.valueOf(s));
        postedDiscuss.setNickName(one.getName());
        postedDiscuss.setCompany(one.getCompany());
        postedDiscuss.setIntro(postedD.getIntro());
        postedDiscuss.setCreateTime(LocalDateTime.now());
        AppletUser byId = appletUserService.getById(Integer.valueOf(s));
        postedDiscuss.setAvatar(byId.getAvatar());
        boolean save = postedDiscussService.save(postedDiscuss);
        if (save){
            Posted byId1 = postedService.getById(postedD.getFId());
            byId1.setCommentNum(byId1.getCommentNum()+1);
            postedService.updateById(byId1);
            return Result.ok(postedDiscuss).message("行业动态添加评论成功");
        }
        return Result.fail(postedDiscuss).message("行业动态添加评论失败");
    }


    @ApiOperation(value = "行业动态删除评论")
    @PostMapping("/delectCommentPinglun")
    public Result delectCommentPinglun(@RequestBody PostedDiscuss postedDiscuss){
        String s = AuthContextUtil.get();
        LambdaQueryWrapper<PostedDiscuss> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PostedDiscuss::getAppletUserId,Integer.valueOf(s)).eq(PostedDiscuss::getPostedid,postedDiscuss.getPostedid());
        boolean b = postedDiscussService.remove(wrapper);

        if (b){

            Posted byId = postedService.getById(postedDiscuss.getPostedid());
            byId.setCommentNum(byId.getCommentNum()-1);
            return Result.ok().message("删除行业动态的评论成功");
        }
        return Result.fail().message("删除行业动态的评论失败");
    }

    @ApiOperation(value = "/行业动态添加点赞")
    @PostMapping("savaUpvote")
    public Result savaUpvote(@RequestBody Posted posted) {

        Upvote up = new Upvote();
        String s = AuthContextUtil.get();
        LambdaQueryWrapper<Upvote> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Upvote::getDynamicid,posted.getId()).eq(Upvote::getAppletUserId,Integer.valueOf(s));

        Upvote one = upvoteService.getOne(wrapper);
        if (one!=null){
            return Result.ok(one);
        }else {
            up.setCommentid(1);
            up.setDynamicid(posted.getId());

            AppletUser byId = appletUserService.getById(Integer.valueOf(s));
            up.setAvatar(byId.getAvatar());
            up.setAppletUserId(byId.getId());
            boolean save = upvoteService.save(up);
            if (save) {
                Posted byId1 = postedService.getById(posted.getId());
                byId1.setUpvoteNum(byId1.getUpvoteNum() + 1);
                boolean b = postedService.updateById(byId1);

                return Result.ok().message("点赞成功");
            }
            return Result.fail().message("点赞失败");
        }
    }

    @ApiOperation(value = "行业动态取消点赞")
    @PostMapping("/delectUpvoteLike")
    public Result delectUpvote(@RequestBody Posted posted){
        String s = AuthContextUtil.get();
        LambdaQueryWrapper<Upvote> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Upvote::getAppletUserId,Integer.valueOf(s)).eq(Upvote::getDynamicid,posted.getId());
        boolean b = upvoteService.remove(wrapper);

        if (b){

            Posted byId = postedService.getById(posted.getId());
            byId.setUpvoteNum(byId.getUpvoteNum()-1);
            return Result.ok().message("取消行业动态的点赞成功");
        }
        return Result.fail().message("取消行业动态的点赞失败");
    }


    @ApiOperation(value = "行业动态分享数量增加")
    @PostMapping("/saveShareNum")
    public Result saveShareNum(@RequestBody Posted posted){

        Posted byId = postedService.getById(posted.getId());
        byId.setShareNum(byId.getShareNum()+1);
        boolean b = postedService.updateById(posted);
        if (b){
            return Result.ok().message("增加分享数量成功");
        }

        return Result.fail().message("增加分享数量失败");
    }
}

